package com.dlc.felear.xiaoensale.customView;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.adapter.DeviceListtemAdapter;
import com.dlc.felear.xiaoensale.entity.DeviceInfo;

import java.util.List;


public class DevicesListViewDialog extends Dialog implements AdapterView.OnItemClickListener ,View.OnClickListener{
    private static final String TAG="ListViewDialog";
    private Button  btnConfirm;
    private Context context;
    private OnclickItemCallback callback;
    private ListView listView;
    private DeviceListtemAdapter adapter;

    public DevicesListViewDialog(@NonNull Context context, OnclickItemCallback callback) {
        super(context);
        this.callback = callback;
        initView(context);
    }


    public DevicesListViewDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        initView(context);
    }

    private void initView(Context context) {
        this.context = context;
        View root = LayoutInflater.from(context).inflate(R.layout.listview_select_dialog, null);
        btnConfirm = root.findViewById(R.id.btn_confirm);
        adapter=new DeviceListtemAdapter(context);
        listView = root.findViewById(R.id.lv);
        btnConfirm.setOnClickListener(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        setContentView(root);
        setCanceledOnTouchOutside(true);
    }



    public void showDialog(List<DeviceInfo> list) {
        adapter.setItems(list);
        show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                clearData();
                dismiss();
                break;
            default:
        }
    }

    private void clearData() {
        DeviceInfo deviceInfo=null;
        for(DeviceInfo d:adapter.getData()){
            if(d.isSelect()){
                deviceInfo=d;
                break;
            }
        }
        if(deviceInfo==null){
            showToast("请选择炒菜设备");
            return;
        }
        if(callback!=null){
            callback.onclickItem(deviceInfo);
        }
    }



    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        adapter.updateStatus(position);
    }

    public interface OnclickItemCallback {
        void onclickItem(DeviceInfo deviceInfo);
    }
}
